package com.cz.run.web;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.cz.run.beans.base.PageDTO;
import com.cz.run.beans.base.ReturnDTO;
import com.cz.run.beans.mysql.*;
import com.cz.run.beans.po.task.AreaPriceCode;
import com.cz.run.beans.po.task.ListPO;
import com.cz.run.beans.po.task.ReleasePO;
import com.cz.run.beans.po.task.TaskDetail;
import com.cz.run.beans.vo.task.TaskDetailVO;
import com.cz.run.beans.vo.task.TaskVO;
import com.cz.run.constants.ConstantKey;
import com.cz.run.service.*;
import com.cz.run.utils.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @Description: TODO()
 * @auther:CAIYJ
 * @Date:2018/5/27 14:13
 */
@Api(value = "任务模块")
@RestController
@RequestMapping(value = "/task")
public class TaskServer {

    @Autowired
    private ITaskService taskService;

    @Autowired
    private IUserPointService iUserPointService;

    @Autowired
    private IAdvertisementService advertisementService;

    @Autowired
    private IAreaCodeService iAreaCodeService;

    @Autowired
    private ITaskLogService iTaskLogService;

    @Autowired
    private IUserForceDynamicService iUserForceDynamicService;

    @ApiOperation(value = "广告列表", notes = "广告列表", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequestMapping(value = "/list")
    public ReturnDTO list(@RequestBody ListPO po) throws Exception {
        Page<Task> page = new Page<>(po.getCurrentPage(), po.getPageSize());
        EntityWrapper<Task> ew = new EntityWrapper<>();
        ew.where("audit_status = {0}", 1);
        ew.and(StringUtils.isNotEmpty(po.getCode()), "code = {0}", po.getCode());
        ew.and(po.getType() != null, "type = {0}", po.getType());
        page = taskService.selectPage(page);
        PageDTO<TaskVO> pageDTO = new PageDTO<>();
        if (null != page && null != page.getRecords() && page.getRecords().size() > 0) {
            List<TaskVO> list = new ArrayList<>();
            TaskVO vo = null;
            Set<Integer> set = new HashSet<>();
            for (Task task : page.getRecords()) {
                set.add(task.getId());
                vo = new TaskVO();
                BeanUtils.copyProperties(task, vo);
                list.add(vo);
            }
            if (set.size() > 0) {
                EntityWrapper<Advertisement> aew = new EntityWrapper<>();
                aew.in("task_id", set);
                List<Advertisement> advertisements = advertisementService.selectList(aew);
                if (null != advertisements && advertisements.size() > 0) {
                    out:
                    for (TaskVO taskVO : list) {
                        for (Advertisement advertisement : advertisements) {
                            if (taskVO.getId().equals(advertisement.getTaskId())) {
                                taskVO.setImage(advertisement.getImage());
                                continue out;
                            }
                        }
                    }
                }
            }
            pageDTO.setContent(list);
            pageDTO.setTotalRecord(page.getTotal());
        }
        return ReturnDTO.success(pageDTO);
    }

    @ApiOperation(value = "发布任务", notes = "发布任务", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequestMapping(value = "/release")
    public ReturnDTO<String> release(@RequestBody ReleasePO po, HttpServletRequest request) throws Exception {
        String userId = (String) request.getAttribute(ConstantKey.USER_KEY);
        Task task = new Task();
        BeanUtils.copyProperties(po, task);
        taskService.insert(task);

        EntityWrapper<UserPoint> uew = new EntityWrapper<>();
        uew.where("user_id={0}",userId);
        UserPoint userPoint =iUserPointService.selectOne(uew);

        if(userPoint.getPoint()<po.getIntegral()){
            return ReturnDTO.fail("积分不够");
        }
        userPoint.setPoint(userPoint.getPoint()-po.getIntegral());
        userPoint.setPointFrozen(userPoint.getPointFrozen()+po.getIntegral());

        iUserPointService.updateById(userPoint);

        return ReturnDTO.success("发布成功");
    }

    @ApiOperation(value = "获取区域价格", notes = "获取区域价格", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequestMapping(value = "/areaPrice")
    public ReturnDTO<Double> areaPrice(@RequestBody AreaPriceCode areaPriceCode, HttpServletRequest request) throws Exception {

        if(null==areaPriceCode||StringUtils.isEmpty(areaPriceCode.getCode())){
            return  ReturnDTO.fail("参数为空");
        }

        EntityWrapper<AreaCode> uew = new EntityWrapper<>();
        uew.where("code={0}",areaPriceCode.getCode());
        AreaCode areaCode =iAreaCodeService.selectOne(uew);

        return ReturnDTO.success(null!=areaCode?areaCode.getPrice():0);
    }

    @ApiOperation(value = "获取任务详情", notes = "获取任务详情", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequestMapping(value = "/taskDetail")
    public ReturnDTO<TaskDetailVO> taskDetail(@RequestBody TaskDetail taskDetail, HttpServletRequest request) throws Exception {

        if(null==taskDetail||null==taskDetail.getTaskId()){
            return ReturnDTO.fail("参数不能为空");
        }

        String userId = (String) request.getAttribute(ConstantKey.USER_KEY);
        EntityWrapper<Task> uew = new EntityWrapper<>();
        uew.where("id={0}",taskDetail.getTaskId());
        Task task =taskService.selectOne(uew);

        TaskDetailVO taskDetailVO = new TaskDetailVO();

        EntityWrapper<TaskLog> ew = new EntityWrapper<>();
        ew.where("task_id={0} and user_id={1}",taskDetail.getTaskId(),userId);
        TaskLog taskLog =iTaskLogService.selectOne(ew);

        taskDetailVO.setFlag(null!=taskLog);
        taskDetailVO.setUrl(task.getUrl());

        return ReturnDTO.success(taskDetailVO);
    }

    @ApiOperation(value = "完成任务", notes = "完成任务", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequestMapping(value = "/finishTask")
    public ReturnDTO<String> finishTask(@RequestBody TaskDetail taskDetail, HttpServletRequest request) throws Exception {
        String userId = (String) request.getAttribute(ConstantKey.USER_KEY);

        if(null==taskDetail||null==taskDetail.getTaskId()){
            return ReturnDTO.fail("参数不能为空");
        }

        EntityWrapper<Task> uew = new EntityWrapper<>();
        uew.where("id={0}",taskDetail.getTaskId());
        Task task =taskService.selectOne(uew);

        TaskDetailVO taskDetailVO = new TaskDetailVO();

        EntityWrapper<TaskLog> ew = new EntityWrapper<>();
        ew.where("task_id={0} and user_id={1}",taskDetail.getTaskId(),userId);
        TaskLog taskLog =iTaskLogService.selectOne(ew);

        if(null!=taskLog){
            return ReturnDTO.error("已完成");
        }
         taskLog = new TaskLog();
        taskLog.setTaskId(taskDetail.getTaskId());
        taskLog.setUserId(Integer.parseInt(userId));
        iTaskLogService.insert(taskLog);

        EntityWrapper<UserForceDynamic> userForceDynamicEntityWrapper = new EntityWrapper<>();
        userForceDynamicEntityWrapper.where("user_id={0} and time = {1}",userId,DateUtil.getDateAfterDayYYYYMMDD(new Date(), 0));
        UserForceDynamic userForceDynamic =iUserForceDynamicService.selectOne(userForceDynamicEntityWrapper);
        if(null!=userForceDynamic){
            userForceDynamic.setTemp(userForceDynamic.getTemp()+task.getIntegral());
            iUserForceDynamicService.updateById(userForceDynamic);
        }else{
            userForceDynamic = new UserForceDynamic();
            userForceDynamic.setTemp(task.getIntegral());
            userForceDynamic.setUserId(Integer.parseInt(userId));
            userForceDynamic.setStep(0);
            userForceDynamic.setTime(new Date());
            iUserForceDynamicService.insert(userForceDynamic);
        }

        return ReturnDTO.success("成功");
    }
}
